package com.secure;

import java.math.BigInteger;
import java.util.Random;
import java.io.*;

public class RSA {
	
	private BigInteger N;
	private BigInteger e;
	private BigInteger d;
	
	// Set the bit length of our large primes.
	public static final int SIZE = 512;

	// This method prompts the user for a message,
	// encrypts it using N and e and returns the ciphertext.
	public String encodeMessage(String msg, BigInteger N,
			BigInteger d) throws IOException {
		// Get a message to encrypt.
		BigInteger message = new BigInteger(msg.getBytes());
		;

		while ((message.compareTo(N) != -1)
				|| (message.gcd(N).compareTo(BigInteger.valueOf(1)) != 0))
			;

		// Encrypt the message
		BigInteger ciphertext = message.modPow(d, N);

		// Return the ciphertext
		return ciphertext.toString();
	}

	// Generate keys, get encrypted message and decrypt it.
	public static void main(String[] argv) throws IOException {
		
		new RSA();
	}

	public void rsaKeyGen() {
		BigInteger p, q, PhiN;

		// Generate two distinct large prime numbers p, q
		p = new BigInteger(SIZE, 10, new Random());
		do {
			q = new BigInteger(SIZE, 10, new Random());
		} while (q.compareTo(p) == 0);

		// Calculate their product
		N = p.multiply(q);

		// And calculate PhiN = (p-1)(q-1)
		PhiN = p.subtract(BigInteger.valueOf(1));
		PhiN = PhiN.multiply(q.subtract(BigInteger.valueOf(1)));

		// Next choose e, coprime to and less than PhiN
		do {
			e = new BigInteger(2 * SIZE, new Random());
		} while ((e.compareTo(PhiN) != -1)
				|| (e.gcd(PhiN).compareTo(BigInteger.valueOf(1)) != 0));

		// Compute d, the inverse of e mod PhiN
		d = e.modInverse(PhiN);
		
		
	}

	public String decodeMessage(String msg, BigInteger N,BigInteger e){
		BigInteger pt = new BigInteger(msg);
		return new String(pt.modPow(e, N).toByteArray());
	}
	
	
	public RSA(){
		
	}

	public BigInteger getN() {
		return N;
	}

	public BigInteger getE() {
		return e;
	}

	public BigInteger getD() {
		return d;
	}
	
	
	
}
